import { _decorator, Component, EditBox, Node } from 'cc';
const { ccclass, property } = _decorator;
import Crypt from 'jsencrypt';
import { PublicKey, RpcFunc } from '../common';
import NetworkManager from '../global/NetworkManager';

// 引入 RSA 公钥
const crypt = new Crypt();
crypt.setKey(PublicKey)

@ccclass('Login')
export class Login extends Component {

    @property(EditBox)
    account: EditBox = null;

    @property(EditBox)
    password: EditBox = null;

    protected onLoad(): void {

    }

    start() {

    }

    async register() {
        const account = crypt.encrypt(this.account.string);
        const password = crypt.encrypt(this.password.string);

        const res = await fetch("http://localhost:3000/register", {
            method: "POST",
            body: JSON.stringify({
                account,
                password,
            }),
            headers: {
                "Content-Type": "application/json",
                // 'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
            .then((response) => {
                return response.json();
            })
        console.log("res", res);
    }


    async login() {
        const account = crypt.encrypt(this.account.string);
        const password = crypt.encrypt(this.password.string);

        const res = await fetch("http://localhost:3000/login", {
            method: "POST",
            body: JSON.stringify({
                account,
                password,
            }),
            headers: {
                "Content-Type": "application/json",
                // 'Content-Type': 'application/x-www-form-urlencoded',
            },
        })
            .then((response) => {
                return response.json();
            })

        this.connet(res.token);
    }

    async connet(token: string) {
        await NetworkManager.Instance.connect();
        const res = await NetworkManager.Instance.call(RpcFunc.enterGame, {
            token,
        })
        console.log("connect", res);
    }

    update(deltaTime: number) {

    }
}


